package com.example.mongodb.mongodb.config;



import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 启动了rabbitmq 的延迟队列
 * 这里定义了一个延迟队列
 *
 */

@Configuration
@EnableRabbit
public class DelayedQueueConfig {

    @Bean
    public Queue queue(){
        Queue queue = new Queue("q.delayed",false,false,false,null);
        return queue;
    }

    @Bean
    public Exchange exchange(){
        Map<String,Object> map = new HashMap<>();
        map.put("x-delayed-type", ExchangeTypes.DIRECT);
        // 使用x-delayed-message表示使用delayed  exchange插件处理消息
        Exchange exchange = new CustomExchange("ex.delayed","x-delayed-message",true,false,map);
        return exchange;
    }

    @Bean
    public Binding binding(){
        return BindingBuilder.bind(queue()).to(exchange()).with("key-delayed").noargs();
    }



    @Bean
    @Autowired
    public RabbitAdmin amqpAdmin(ConnectionFactory connectionFactory){
       return  new RabbitAdmin(connectionFactory);
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory = new SimpleRabbitListenerContainerFactory();
        simpleRabbitListenerContainerFactory.setConnectionFactory(connectionFactory);
        //手动确认消息
        simpleRabbitListenerContainerFactory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        //设置并发线程数
        simpleRabbitListenerContainerFactory.setConcurrentConsumers(10);
        //设置最大并发线程数
        simpleRabbitListenerContainerFactory.setMaxConcurrentConsumers(20);
        return simpleRabbitListenerContainerFactory;
    }



}
